package org.linlinjava.litemall.core.util.pay;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.linlinjava.litemall.core.config.AliPayConfig;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: zhou
 * @Description:
 * @Date:Create in 2019/01/14
 * @Modified By:
 */

@Component
public class AlipayUtils {

    /**
     * 校验签名
     *
     * @param request
     * @return
     */
    public boolean rsaCheck(HttpServletRequest request) throws UnsupportedEncodingException {

        /**
         *  获取支付宝POST过来反馈信息
         */
        Map<String, String> params = new HashMap<>(1);
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        try {
            boolean verifyResult = AlipaySignature.rsaCheckV1(params, AliPayConfig.ALIPAY_PUBLIC_KEY, "UTF-8", AliPayConfig.SIGN_TYPE);
            return verifyResult;
        } catch (AlipayApiException e) {
            return false;
        }
    }


    /**
     * 支付宝退款接口
     *
     * @param out_trade_no  订单支付时传入的商户订单号,不能和支付宝交易号（trade_no）同时为空。
     * @param trade_no      支付宝交易号
     * @param refund_amount 需要退款的金额，该金额不能大于订单金额,单位为元，支持两位小数
     * @return 将提示信息返回
     */
    public synchronized static String alipayRefundRequest(String out_trade_no, String trade_no, double refund_amount) {
        String returnStr = null;

        String out_request_no = "BZ35581R88001";//随机数  不是全额退款，部分退款使用该参数
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.GATEWAY_URL, AliPayConfig.APP_ID, AliPayConfig.RSA_PRIVATE_KEY, AliPayConfig.FORMAT, AliPayConfig.CHARSET, AliPayConfig.ALIPAY_PUBLIC_KEY, AliPayConfig.SIGN_TYPE);
            AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + out_trade_no + "\"," +
                    "\"trade_no\":\"" + trade_no + "\"," +
                    "\"refund_amount\":\"" + refund_amount + "\"," +

                    "\"out_request_no\":\"" + out_request_no + "\"," +
                    "\"refund_reason\":\"正常退款\"" +
                    " }");
            AlipayTradeRefundResponse response = alipayClient.execute(request);
            if (response.isSuccess()) {
                System.out.println("支付宝退款成功");
                returnStr = "支付宝退款成功";
            } else {
                returnStr = response.getSubMsg();//失败会返回错误信息
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnStr;
    }
}
